package io.shuttle.mbe_app.components

import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.annotation.RequiresApi
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext

@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun CustomHapticView() {
    var hapticEngine by remember { mutableStateOf<VibrationEffect?>(null) }
    val context = LocalContext.current
    LaunchedEffect(Unit) {
        val numberOfPulses = 3
        val pulseDuration = 50L
        val spaceBetweenPulses = 100L
        val maxAmplitude = 255
        val timings = LongArray(numberOfPulses * 2)
        val amplitudes = IntArray(numberOfPulses * 2)
        for (i in 0 until numberOfPulses) {
            val amplitude = (maxAmplitude * (i + 1) / numberOfPulses)
            timings[i * 2] = spaceBetweenPulses
            timings[i * 2 + 1] = pulseDuration
            amplitudes[i * 2] = 0
            amplitudes[i * 2 + 1] = amplitude
        }
        hapticEngine = VibrationEffect.createWaveform(timings, amplitudes, -1)
    }
    Button(onClick = {
        hapticEngine?.let {
            val vibrator = context.getSystemService(Vibrator::class.java)
            vibrator.vibrate(it)
        }
    }) {
        Text("Play Custom Haptic!")
    }
}